<?php

namespace common\modules\upload\models;

use yii\base\Model;
use yii\web\UploadedFile;

class UploadForm extends Model
{

    /**
     * @var UploadedFile
     */
    public $imageFile;

    /**
     * @var string 保存目录
     */
    public $saveDir = '';

    /**
     * @var string
     */
    public $uploadUrl = '';

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    /**
     * @return bool
     */
    public function upload()
    {
        if ($this->validate())
        {
            $fileName = md5($this->imageFile->baseName . microtime(true))  . '.' . $this->imageFile->extension;
            if ($this->imageFile->saveAs($this->saveDir . '/' . $fileName))
            {
                $this->uploadUrl .= '/' . $fileName;
                return true;
            }
        }
        return false;
    }
}
